<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :leftType="'1'" @clickLeftBack="clickLeftBack"
				:title="$t('mexico.semiFinishedDefective')" :rightText="$t('distributedEnter.scanRecord')"
				@clickRight="clickRight"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class=" page-auto" :style="'height: calc(100vh - ' + navHeight + 'px);'">
				<view class="gui-bg-white gui-dark-bg-level-3 gui-padding-x distributed-head">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('translationImage.materialsInformation') }}
					</view>
					<view class="custom-card-itemTwo" style="padding: 10rpx 0;display: flex;">
						<text class="item-info-title" style="padding-right: 40rpx;">{{ $t('mexico.typeProduct')
						}}：</text>
						<uni-data-select class="data-select" v-model="data.typeFinished"
							:disabled="data.scanList.length > 0" :localdata="data.finishedOptions" @change="change"
							@click="changeClick"></uni-data-select>
					</view>
					<!-- <view class="custom-card-itemTwo cradItem" style="padding: 20rpx 0;"
						v-show="data.typeFinished != 'PVC' && data.typeFinished != 'LVT' && data.typeFinished != ''">
						<text class="item-info-title" style="padding-right: 40rpx;"><text
								class="required-color">*</text>{{ $t('mexico.isScanCode') }}：</text>
						<view><radio-group @change="radioChange">
								<label class="radio" style="margin-right: 30rpx;">
									<radio value="1" :checked="data.checked == 1" />{{ $t('index.yes') }}
								</label>
								<label class="radio" style="margin-right: 20rpx;">
									<radio value="2" :checked="data.checked == 2" />{{ $t('index.no') }}
								</label>
							</radio-group>
						</view>
					</view> -->
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title"><text
								class="required-color">*</text>{{ $t('hardwareOut.materialsDepartment') }}：</text>
						<superweiCombox style="text-align: right;" :candidates="data.peportmentList"
							:placeholder="$t('distributedOut.placeholder')" :isJSON="true" keyName="text"
							v-model="data.department" @select="departmentSelect"></superweiCombox>
					</view>
					<!-- 扫描条码部分 -->
					<view class="custom-card-itemTwo cradItem" style="padding: 20rpx 0;">
						<!-- v-show="data.checked == 1 || data.typeFinished == 'PVC' || data.typeFinished == 'LVT'" -->
						<text class="item-info-title" style="padding-right: 40rpx;"><text
								class="required-color">*</text>{{ $t('distributedEnter.barcodeScan') }}：</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.scanValue"
							:placeholder="$t('stockManage.pleaseScanCode')" @confirm="confirm" @iconClick="iconClick">
						</uni-easyinput>
					</view>
					<view class="custom-card-itemTwo" style="padding: 10rpx 0;" v-show="data.checked == 2">
						<text class="item-info-title"><text
								class="required-color">*</text>{{ $t('distributedEnter.materialCode') }}：</text>
						<comboGrid requestUrl="/api1/wms/semiProductErrorCrush/GetCrushMaterialCode" :calculate="false"
							v-model="data.materialCode" :requestParam="data.materialParam" inputKey="materialCode"
							:crushType="true" :placeholder="$t('distributedEnter.placeholderTextChoose')"
							:gridPlaceholder="$t('Common.enterCodeOrName')" :column="data.columnName.column"
							bindValue="materialName" @setClick="getMaterialClick">
						</comboGrid>
					</view>
					<view class="custom-card-itemTwo cradItem" style="padding: 20rpx 0;" v-show="data.checked == 2">
						<text class="item-info-title" style="padding-right: 40rpx;"><text
								class="required-color">*</text>{{ $t('distributedEnter.qty') }}：</text>
						<uni-easyinput class="uni-mt-5" v-model="data.numbers" type="number"
							:placeholder="$t('hardwareOut.pleaseQty')">
						</uni-easyinput>
					</view>
					<view class="custom-card-itemTwo cradItem" style="padding: 20rpx 0;"
						v-show="data.checked != null && data.checked != ''">
						<text class="item-info-title" style="padding-right: 40rpx;">{{ $t('materials.remark') }}：</text>
						<uni-easyinput class="uni-mt-5" v-model="data.remark">
						</uni-easyinput>
					</view>
				</view>
				<!-- 提示信息 -->
				<view class="gui-flex gui-rows gui-nowrap gui-align-items-center gui-margin-top">
					<view class="gui-title-line"></view>
					<text class="gui-primary-text gui-h6" style="padding-left:50rpx; padding-right:50rpx;">{{
						$t('translationImage.materialsInformation')
						}}</text>
					<view class="gui-title-line"></view>
				</view>
				<!-- 卡片模块 -->
				<scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll element-auto">
					<view style="height: 15rpx"></view>
					<view v-if="data.barcodeInfo" class="card-boxCustom">
						<view class="card-body">
							<view class="custom-card-title">
								<text class="title-line"></text>
								{{ $t('distributedOut.atPresent') }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.materialCoded')
								}}：</text>{{ data.barcodeInfo.barcode }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.materialCode') }}：</text>
								{{ data.barcodeInfo.materialCode }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.materialName') }}：</text>
								{{ data.barcodeInfo.materialName }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.materialSpec')
								}}：</text>{{ data.barcodeInfo.materialSpec }}
							</view>
							<view class="custom-card-itemOne">
								<view class="card-item-50">
									<text class="body-item-title">{{ $t('distributedEnter.uom') }}：</text>
									{{ data.barcodeInfo.unit }}
								</view>
								<view class="card-item-50">
									<text class="body-item-title">{{ $t('distributedEnter.qty') }}：</text>
									{{ data.barcodeInfo.currentQty }}
								</view>
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedOut.warehouse') }}：</text>
								{{ data.barcodeInfo.warehouseCode }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedOut.location') }}：</text>
								{{ data.barcodeInfo.locationCode }}
							</view>
						</view>
					</view>
				</scroll-view>
				<!-- 底部确定按钮 -->
				<view class="page-bottom-box bottom-postion">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="submitClick">
						{{ $t('calendar.submit') }}</view>
				</view>
			</view>
			<!-- 弹框填写数量 -->
			<uni-popup ref="inputDialog" type="center">
				<view v-if="data.barcodeInfo" class="input-dialog-box">
					<view class="input-dialog-content">
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialCode') }}:{{ data.barcodeInfo.materialCode }}
						</view>
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialName') }}:{{ data.barcodeInfo.materialName }}
						</view>
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialSpec') }}:{{ data.barcodeInfo.materialSpec || '' }}
						</view>
						<view class="input-dialog-item">
							{{ $t('distributedEnter.uom') }}:{{ data.barcodeInfo.unit }}
						</view>
						<view class="input-dialog-item">
							{{ $t('pageTranslation.qtyOfDelivery') }}:{{ data.barcodeInfo.inputNum }}
						</view>
						<view class="input-dialog-item flexclass" style="color: #dd524d">
							<view>{{ $t('distributedEnter.qty') }}：</view>
							<view class="input-dialog-item-count">
								<input v-model="data.barcodeInfo.currentQty" type="number"
									:placeholder="$t('JsInternational.plsReturn')" />
							</view>
						</view>
					</view>
					<view class="input-dialog-footer">
						<view class="input-dialog-button" @click="cancelFn">
							{{ $t('popup.cancel') }}
						</view>
						<view class="input-dialog-button dialog-button-left" @click="confirmFn">
							{{ $t('popup.confirm') }}
						</view>
					</view>
				</view>
			</uni-popup>
		</template>
	</gui-page>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { navigate, navigateBack } from '@/utils/routerSkip.js';
import { getDataDictionaryFn, pitchOnFn, pitchOnFn2 } from '@/utils/index.js'
import storageBin from '@/components/storageBin.vue';
import comboGrid from "@/components/comboGrid";
import { useStore } from "vuex";
import { onShow } from '@dcloudio/uni-app';
import { basPdaOperationLogFn } from '@/utils/index.js';
import pdaScan from '@/hooks/pdaScan.js'
import spChooseBox from '@/components/spChooseBox';
import chooseSelect from '@/components/chooseSelect';
import { onBackPress } from '@dcloudio/uni-app';
import { OPERATION_COMMIT, OPERATION_SCAN, DEFAULT_WAREHOUSECODE, DEFAULT_WAREHOUSENAME, DEFAULT_WAREHOUSEID } from '@/constant/index.js'
import superweiCombox from '@/components/superweiCombox';
import { scanSemiProductBarcode, submitSemiProductErrorCrush } from '@/api/api.js'
//JS国际化引入
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

const { scan } = pdaScan()
//注册组件
components: {
	storageBin,
		comboGrid,
		spChooseBox,
		chooseSelect,
		superweiCombox
}

let store = useStore();
//页面弹框输入数量使用的变量
let inputDialog = ref(null)

const data = reactive({
	warehouseName: '',
	warehouseId: '',
	warehouseCode: '',
	scanBarcode: '',//扫描条码
	barcodeInfo: null, //存储后端返回的数据,card的信息
	scanList: [],// 扫描的条码信息
	checked: null,//物料代码下面的筛选
	materialCode: '',
	materialId: '',
	numbers: null,
	scanValue: '',
	// 物料代码
	materialParam: {
		crushType: 'THOutput',
		materialCode: "",
		materialName: "",//物料代码,传给接口用的变量
		text: ""
	},
	columnName: {
		column: [{
			label: t('distributedEnter.materialCode'),
			name: "materialCode",
		}, {
			label: t('distributedEnter.materialName'),
			name: "materialName",
		}, {
			label: t('distributedEnter.materialSpec'),
			name: "materialSpec",
		}]
	},
	typeFinished: '', // 半成品类型
	deportmentCode: '', //领料部code
	department: '', //领料部门
	departmentCode: '',
	remark: '',//备注
	finishedOptions: [
		{ value: 'PVC', text: t("taskList.foamBoard") },
		{ value: 'LVT', text: t("taskList.topSubstrate") },
		{ value: 'THOutput', text: t("taskList.THOutput") },
		{ value: 'JKJOutput', text: t("taskList.JKJOutput") },
		{ value: 'PEOutput', text: t("taskList.PEOutput") },
	],
})
const navHeight = computed(() => {
	return store.state.navHeight
})

onShow(async () => {
	// 没有设置默认仓库去设置默认仓库  原始仓库的赋值
	data.warehouseName = uni.getStorageSync(DEFAULT_WAREHOUSENAME) || ''
	data.warehouseId = uni.getStorageSync(DEFAULT_WAREHOUSENAME) || ''
	data.warehouseCode = uni.getStorageSync(DEFAULT_WAREHOUSECODE) || ''
	if (data.warehouseName == '') {
		uni.showModal({
			content: t('materials.pleaseSetTheDefault'),
			showCancel: false,
			confirmText: t('pageTranslation.toSet'),
			success: function (res) {
				if (res.confirm) {
					uni.navigateTo({
						url: '/pages/setting/warehouse'
					})
				} else if (res.cancel) {

				}
			}
		});
	}
})


//监听pda扫码
onMounted(() => {
	uni.$on('scancodedate', (data) => {
		// console.log('获取到的code：' + data.code)
		getCode(data.code, 'pda')
	})
	getInitData()
})

data.scanList = computed(() => {
	return store.state.semiFinishedCrushed
})

// 是否扫描
const radioChange = (e) => {
	// console.log(e)
	data.checked = e.detail.value
}

// 下拉框选择
const change = (e) => {
	data.typeFinished = e
	data.materialParam.crushType = e
	data.scanValue = ''
}

const changeClick = () => {
	if (data.scanList.length > 0) {
		uni.showToast({ title: t('taskList.pleaseSubmit'), icon: "none" });
	}
	data.checked = ''
}

const getInitData = async () => {
	// 获取领料人数据
	await getDataDictionaryFn('Deportment').then(res => {
		data.peportmentList = res.data
	})
	let arr = data.peportmentList.filter(x => x.remark?.includes(data.warehouseCode))
	data.peportmentList = arr
	let tepSelect1 = pitchOnFn2(data.peportmentList)
	if (tepSelect1.length == 0) return
	console.log(tepSelect1)
	data.department = tepSelect1[0].text // 默认选中第一个 text
	data.departmentCode = tepSelect1[0].value  // 默认选中第一个 value
}
// 领料部门选择
const departmentSelect = (e) => {
	data.department = e.text
	data.departmentCode = e.value
}

//物料名称的选择
const getMaterialClick = (x) => {
	data.materialParam.materialCode = x.materialCode;
	data.materialParam.materialName = x.materialName;
	data.materialCode = x.materialCode;
	data.materialName = x.materialName;
	data.unit = x.unit
	data.materialSpec = x.specification
	data.materialId = x.id
}

// 用户调起相机扫码
const iconClick = async (type) => {
	if (type === 'suffix') {
		let code = await scan()
		getCode(code, 'scan')
	}
}

// 用户点击键盘上搜索
const confirm = () => {
	getCode(data.scanValue, 'keydown')
}

// 获取code，查询barcode信息
const getCode = (code, type) => {
	//判断是否扫描过该条码
	var exist = data.scanList.filter(e => e.barcode == code);
	if (exist.length > 0) {
		uni.showToast({
			title: t('distributedOut.repeatScan'),
			icon: 'error'
		})
		return;
	}
	let parmes = {
		barcode: code,
		crushType: data.typeFinished
	}
	uni.showLoading({
		title: 'loading',
		mask: true
	});

	scanSemiProductBarcode(parmes).then(res => {
		//隐藏加载框
		uni.hideLoading();
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '半成品次品粉碎'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SCAN,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		console.log(res)
		if (res.code == 0) {
			data.barcodeInfo = res.data
			data.barcodeInfo.remark = data.remark
			data.barcodeInfo.inputNum = data.barcodeInfo.currentQty
			let materialCode = res.data.materialCode;
			// console.log('data.scanList.length',data.scanList.length)
			if (data.scanList?.length == 0) {
			} else {
				var existMaterialCode = data.scanList.some(e => e.materialCode == materialCode)
				if (!existMaterialCode) {
					uni.showToast({
						title: t('stockManage.fgInstore'),
						icon: 'none'
					})
					return
				}
			}
			inputDialog.value.open()
		} else {
			uni.showToast({ title: res.msg, icon: "none" });
		}
	})
}
//扫描条码  弹框的确定按钮
const confirmFn = () => {
	if (data.barcodeInfo.currentQty == null || data.barcodeInfo.inputNum < data.barcodeInfo.currentQty) {
		uni.showToast({ title: t('hardwareOut.pleaseQty'), icon: "none" });
		return
	}
	if (Number(data.barcodeInfo.currentQty) == 0) {
		uni.showToast({ title: t('JsInternational.qtyCant'), icon: "none" });
		return
	}
	store.commit('addSemiFinishedCrushed', data.barcodeInfo)
	uni.showToast({ title: t('JsInternational.dataSaved'), icon: "none" });
	inputDialog.value.close();
}
// 扫描条码  弹框的取消按钮
const cancelFn = () => {
	data.barcodeInfo = undefined
	inputDialog.value.close();
}
// 提交 
const submitClick = () => {
	// 领料部门
	if (!data.department) {
		uni.showToast({
			title: t('JsInternational.chooseDept'),
			icon: 'none'
		})
		return
	}
	let parmes = {
		crushType: data.typeFinished,
		remarks: data.remark,
		scanFlag: true,
		deptCode: data.departmentCode,
	}
	let arr = []
	data.scanList.forEach(item => {
		arr.push({
			id: item.id,
			barcode: item.barcode,
			materialCode: item.materialCode,
			crushQty: item.currentQty,
		})
	})
	parmes.lstBarcodeItem = arr
	// if (data.typeFinished == 'LVT' || data.typeFinished == 'PVC') {
	// 	if (!data.scanList.length) {
	// 		uni.showToast({
	// 			title: t('pageTranslation.pleaseScan'),
	// 			icon: 'none'
	// 		})
	// 		return
	// 	}
	// 	parmes.scanFlag = true
	// 	let arr = []
	// 	data.scanList.forEach(item => {
	// 		arr.push({
	// 			id: item.id,
	// 			barcode: item.barcode,
	// 			materialCode: item.materialCode,
	// 			crushQty: item.currentQty,
	// 		})
	// 	})
	// 	parmes.lstBarcodeItem = arr
	// } else {
	// 	console.log(data.checked)
	// 	if (data.checked == 1) {
	// 		// 扫描条码
	// 		if (!data.scanList.length) {
	// 			uni.showToast({
	// 				title: t('pageTranslation.pleaseScan'),
	// 				icon: 'none'
	// 			})
	// 			return
	// 		}
	// 		// 领料部门
	// 		if (!data.department) {
	// 			uni.showToast({
	// 				title: t('JsInternational.chooseDept'),
	// 				icon: 'none'
	// 			})
	// 			return
	// 		}
	// 		parmes.scanFlag = true
	// 		let arr = []
	// 		data.scanList.forEach(item => {
	// 			arr.push({
	// 				id: item.id,
	// 				barcode: item.barcode,
	// 				materialCode: item.materialCode,
	// 				crushQty: item.currentQty,
	// 			})
	// 		})
	// 		parmes.lstBarcodeItem = arr
	// 	} else if (data.checked == 2) {
	// 		if (!data.materialCode) {
	// 			uni.showToast({
	// 				title: t('distributedEnter.materialCode'),
	// 				icon: 'none'
	// 			})
	// 			return
	// 		}
	// 		if (!data.numbers || Number(data.numbers) <= 0) {
	// 			uni.showToast({
	// 				title: t('Common.inputNumber'),
	// 				icon: 'none'
	// 			})
	// 			return
	// 		}

	// 		parmes.noScanCrushQty = data.numbers
	// 		parmes.materialCode = data.materialCode
	// 	}
	// }
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	// 调用接口
	submitSemiProductErrorCrush(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '半成品次品粉碎'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.code == 0) {
			//隐藏加载框
			uni.hideLoading();
			//删除已提交的数据
			store.commit('clearSemiFinishedCrushed')
			data.barcodeInfo = undefined
			data.typeFinished = ''
			data.checked = null
			data.scanValue = ''
			data.department = ''
			data.departmentCode = ''
			data.materialCode = ''
			data.numbers = null
			data.remark = ''
			// data.scanList=[]
			uni.showToast({ title: t('smashRemoval.submitSuccessfully'), icon: "none" });
		} else {
			uni.showToast({ title: res.msg, icon: "none" });
		}
	})

}

//扫描纪录
const clickRight = () => {
	navigate({
		url: '/pages/semiFinishedDefectiveSmash/semiFinishedDefectiveSmashRecord'
	})
}

//导航栏左侧返回
const clickLeftBack = () => {
	if (!data.scanList.length) {
		uni.navigateBack({
			delta: 1
		});
		return
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.unsubmittedDataIn'),
		success: function (res) {
			if (res.confirm) {
				store.commit("clearSemiFinishedCrushed")
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}

//点击物理按键的返回
onBackPress((options) => {
	if (options.from == 'backbutton') {
		if (!data.scanList.length) {
			uni.navigateBack({
				delta: 1
			});
			return true
		}
		uni.showModal({
			title: t('smashRemoval.warmPrompt'),
			content: t('materials.unsubmittedDataIn'),
			success: function (res) {
				if (res.confirm) {
					//清除store 里面的数据
					store.commit("clearSemiFinishedCrushed");
					uni.navigateBack({
						delta: 1
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
		return true;
	}
})

</script>


<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
}

.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}

.page-bottom-box {
	position: absolute;
	left: 0rpx;
	bottom: 0rpx;
	width: 100%
}

.item-info-title {
	width: 100px !important;
}

.data-select {
	flex: 1;
	height: 100%;
}
</style>
